<template>
<div>
    <div>
        <PageTitle :title="form.id ? '编辑项目' : '新增项目'"></PageTitle>
        <Form ref="form" class="project-edit-form" :model="form" :rules="formRules" :label-width="80">
            <FormItem label="所属巡演" prop="tour_id" key="tour_id">
                <Select v-model="form.tour_id" clearable filterable style="width: 300px" @on-change="handleChangeTour">
                    <Option v-for="item in tourLists" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </FormItem>
            <FormItem label="所属艺人" prop="singer_id" key="singer_id">
                <Select v-model="form.singer_id" clearable filterable style="width: 300px">
                    <Option v-for="item in singerLists" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </FormItem>
            <FormItem label="项目名称" prop="name" key="name">
                <Input v-model="form.name" placeholder="请填写项目名称" style="width:300px"></Input>
            </FormItem>
            <FormItem label="所在城市" prop="city_id" key="city_id">
                <AreaCascader v-model="form.city_id" :level="2"></AreaCascader>
            </FormItem>
            <FormItem label="所属分类" prop="category_id" key="category_id">
                <Select v-model="form.category_id" clearable style="width: 300px">
                    <Option v-for="item in categories" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </FormItem>
            <FormItem label="项目主图" prop="img" key="img">
                <ImageUpload v-model="form.img"></ImageUpload>
            </FormItem>
            <FormItem label="售卖模式" prop="sale_mode" key="sale_mode">
                <CheckboxGroup v-model="form.sale_mode">
                    <Checkbox label="direct">委托购票</Checkbox>
                    <Checkbox label="agent">委托代拍</Checkbox>
                </CheckboxGroup>
            </FormItem>
            <FormItem label="出票方式" prop="ticket_type" key="ticket_type">
                <CheckboxGroup v-model="form.ticket_type">
                    <Checkbox :label="1">电子票</Checkbox>
                    <Checkbox :label="2">纸质票</Checkbox>
                </CheckboxGroup>
            </FormItem>
            <FormItem label="是否开售" prop="is_sale" key="is_sale" required>
                <RadioGroup v-model="form.is_sale" >
                    <Radio :label="1">是</Radio>
                    <Radio :label="0">否</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="是否有座" prop="is_seat" key="is_seat" required>
                <RadioGroup v-model="form.is_seat" >
                    <Radio :label="1">有座</Radio>
                    <Radio :label="0">无座</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem  label="是否实名" prop="is_realname" key="is_realname" required>
                <RadioGroup v-model="form.is_realname" >
                    <Radio :label="1">需要</Radio>
                    <Radio :label="0">不需要</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="演出地点" prop="address" key="address">
                <Input :value="form.address" readonly style="width:300px"></Input>
                <Button type="info" style="margin-left: 20px;" @click="showMapModal = true">选择地点</Button>
            </FormItem>
            <FormItem label="允许退款" prop="allow_refund" key="allow_refund" required>
                <RadioGroup v-model="form.allow_refund">
                    <Radio :label="0">不允许</Radio>
                    <Radio :label="1">允许</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem v-if="form.allow_refund === 1" label="退款配置">
                <div>
                    <Table :columns="refund_rule_columns" :data="form.refund_rules" border style="width: 640px;">
                        <template slot-scope="{ row, index }" slot="times">
                            <DatePicker v-model="form.refund_rules[index].times" type="datetimerange" format="yyyy-MM-dd HH:mm" placeholder="请选择时间区间" style="width: 100%;" transfer></DatePicker>
                        </template>
                        <template slot-scope="{ row, index }" slot="rate">
                            <InputNumber
                                :min="0"
                                :max="100"
                                :precision="1"
                                style="width: 100%;"
                                v-model="form.refund_rules[index].rate"
                                :formatter="value => `${value}%`"
                                :parser="value => value.replace('%', '')"></InputNumber>
                        </template>
                        <template slot-scope="{ row, index }" slot="delete">
                            <Button type="error" size="small" @click="handleDeleteRule(index)">删除</Button>
                        </template>
                    </Table>
                    <Button type="info" ghost style="margin-top: 10px;" @click="handleAddRule">增加规则</Button>
                </div>
            </FormItem>
            <FormItem v-if="form.allow_refund === 1" label="退款原因" prop="refund_reason" key="refund_reason">
                <Input v-model="form.refund_reason" :rows="6" type="textarea" placeholder="请填写退款原因" style="width: 640px;" />
            </FormItem>
            <FormItem label="服务说明" prop="service_desc" key="service_desc">
                <Input v-model="form.service_desc" :rows="12" type="textarea" placeholder="请填写服务说明" />
            </FormItem>
            <FormItem label="购票须知" prop="instructions" key="instructions">
                <Input v-model="form.instructions" :rows="12" type="textarea" placeholder="请填写购票须知" />
            </FormItem>
            <Tabs>
                <TabPane label="项目描述">
                    <UEditor ref="ueditor"></UEditor>
                </TabPane>
            </Tabs>
        </Form>
        <div style="padding-top: 20px;">
            <Button type="primary" :loading="submiting" @click="handleSubmit" style="width: 100px;">提交</Button>
            <Button :disabled="submiting" @click="handleCancel" style="margin-left: 10px; width: 100px;">取消</Button>
        </div>
    </div>
    
    <Modal
        v-model="showMapModal"
        title="选择演出地点"
        fullscreen
        @on-ok="handleSelectMap"
    >
        <BaiduMap ref="map" :show="showMapModal"></BaiduMap>
    </Modal>
    
    <Spin size="large" fix v-if="isLoading"></Spin>
</div>
</template>

<script>
const orgRule = { times: '', rate: 0 };
import {formatDate, deepClone} from '@/libs/tools.js';
import AreaCascader from "@/components/form/area-cascader.vue";
import ImageUpload from '@/components/form/image-upload.vue';
import UEditor from "@/components/form/ueditor.vue";
import BaiduMap from '@/components/form/b-map.vue';
export default {
    name: "project_edit",
    components: {
        AreaCascader,
        ImageUpload,
        UEditor,
        BaiduMap
    },
    data() {
        return {
            refund_rule_columns: [
                {
                    title: '时间段',
                    slot: 'times'
                },
                {
                    title: '手续费',
                    slot: 'rate'
                },
                {
                    title: '操作',
                    width: 68,
                    slot: 'delete'
                }
            ],
            tourLists: [],
            singerLists: [],
            isLoading: false,
            showMapModal: false,
            submiting: false,
            form: {
                id: '',
                name: '',
                img: '',
                category_id: '',
                tour_id: '',
                singer_id: '',
                sale_mode: ['direct','agent'],
                ticket_type: [],
                is_sale: 1,
                is_seat: 1,
                is_realname: 1,
                city_id: [],
                address: '',
                lat: '',
                lng: '',
                content: '',
                allow_refund: 0,
                refund_rules:[],
                refund_reason: '本项目支持有条件退票，若需要收取退款手续费，将以用户实际支付票款总额为基准收取。基于项目提供的退票政策不同，退款手续费标准详见本项目购票须知退票细则。提交退款申请后，不支持撤回！',
                service_desc: '不支持退/有条件退\n票品为有价证券，非普通商品，其背后承载的文化服务具有时效性、唯一性等特征，如非演出变更、演出取消、票品错误的原因，不提供退换票服务，购票时请务必仔细核对并谨慎下单。\n本项目支持有条件退票，若需要收取退款手续费，将以用户实际支付票款总额为基准收取。基于项目提供的退票政策不同，退款手续费标准详见本项目购票须知退票细则。\n\n实名观演\n本项目须实名制购票及入场，观演人请本人携带购票时填写证件验证入场，购票完成后观演人信息不可更改。\n\n电子票/纸质票\n请在票夹查看电子票，同场次请勿使用同一证件在多家平台购票，以免给您的进场带来不便及不必要的损失。\n不支持修改收货地址和配送方式，请务必在下单前核实您填写的收货地址和手机号码，为保证成功购票，请您使用(中国大陆地区）有效手机号码。临近演出或商家特殊要求的订单支持现场取票，下单后可在订单页查看取票信息。\n\n发票开具\n发票开具方：成都渔娱文化传播有限公司\n该项目支持开具电子发票。该发票由第三方主办提供，需要在演出开始前提交发票申请，一般演出结束后1个月左右开具。',
                instructions: '入场规则\n本场演出采用纸质票并携带观演人相关证件核验入场。\n本场演出采用电子票并携带观演人相关证件核验入场。\n\n实名观演\n本项目须实名制购票及入场，观演人请本人携带购票时填写证件验证入场，购票完成后观演人信息不可更改。\n\n特别说明\n请在票夹查看电子票，同场次请勿使用同一证件在多家平台购票，以免给您的进场带来不便及不必要的损失。\n不支持修改收货地址和配送方式，请务必在下单前核实您填写的收货地址和手机号码，为保证成功购票，请您使用(中国大陆地区）有效手机号码。临近演出或商家特殊要求的订单支持现场取票，下单后可在订单页查看取票信息。\n\n退/换票规则\n票品为有价证券，非普通商品，其背后承载的文化服务具有时效性、唯一性等特征，如非演出变更、演出取消、票品错误的原因，不提供退换票服务，购票时请务必仔细核对并谨慎下单。\n本项目支持有条件退票，若需要收取退款手续费，将以用户实际支付票款总额为基准收取。基于项目提供的退票政策不同，退款手续费标准详见本项目购票须知退票细则。\n\n儿童说明\n一人一票，儿童须持票入场。\n1.2米以下儿童免票，需由购票监护人陪同入场（一名成人仅限携带一名儿童）；1米2以上儿童需持票入场；谢绝婴幼儿入场（由于音乐节现场人员较密集，音量较大，避免给婴幼儿带来不良影响）。\n\n异常排单说明\n对于异常订购行为，票豆有权在订单成立或者生效之后取消相应订单。异常订购行为包括但不仅限于：下单与支付回调时间超过5分钟的异常订单；经合理判断认为非真实消费者的下单行为；通过虚构身份信息或非法资金来源的下单行为。\n\n特殊提示\n因市场变化、不可抗力等客观情形以及演出票随订随售的性质，可能会出现演出变更、取消、或正式出票时票品库存不足等情况，该等情形下票豆客服会及时与您联系并尽快退款。'
            },
            formRules: {
                name: [
                    {required: true, message: "请填写项目名称", trigger: "blur"}
                ],
                img: [
                    {required: true, message: '请上传项目主图', trigger: 'change'}
                ],
                category_id: [
                    {required: true, type: "number", message: "请选择所属品类", trigger: "change"}
                ],
                city_id: [
                    {required: true, type: 'array', message: "请选择演出城市", trigger: "change"}
                ],
                address: [
                    {required: true, message: "请选择演出地点", trigger: "change"}
                ],
                service_desc: [
                    {required: true, message: "请填写服务说明", trigger: "blur"}
                ],
                instructions: [
                    {required: true, message: "请填写购票须知", trigger: "blur"}
                ],
                refund_reason: [
                    {required: true, message: "请填写退款原因", trigger: "blur"}
                ]
            },
            disableDateOptions: {
                disabledDate (date) {
                    return date && date.valueOf() < Date.now() - 86400000;
                }
            }
        };
    },
    computed: {
        categories() {
            return this.$store.state.data.categories;
        }
    },
    mounted() {
        this.$store.dispatch('getCategories');
        if(this.$route.query.id) {
            this.form.id = this.$route.query.id;
            this.handleGetDetail();
        }else{
            this.$nextTick(() => {
                // 初始化ue编辑器
                this.$refs.ueditor.init();
                // 初始化地图
                this.$refs.map.init();
                // 初始化退款规则
                this.form.refund_rules.push(deepClone(orgRule))
            })
        }
        this.init();
    },
    methods: {
        init() {
            this.$ajax.get('/project/tour/index', {params: {pageSize: 1000}}).then(res => {
                this.tourLists = res.items
            }).catch(err => {})
            this.$ajax.get('/project/singer/index', {params: {pageSize: 1000}}).then(res => {
                this.singerLists = res.items
            }).catch(err => {})
        },
        handleChangeTour(e){
            this.tourLists.map(item => {
                if (item.id == e){
                    this.form.name = item.name;
                }
            })
        },
        // 添加规则
        handleAddRule() {
            this.form.refund_rules.push(deepClone(orgRule))
        },
        // 删除规则
        handleDeleteRule(index) {
            this.form.refund_rules.splice(index, 1);
        },
        //获取详情
        handleGetDetail(){
            this.isLoading = true;
            this.$ajax.get('/project/read/'+this.form.id).then(res=>{
                this.isLoading = false;
                // 填充表单数据
                this.form.name = res.name;
                this.form.category_id = res.category_id;
                this.form.tour_id = res.tour_id;
                this.form.singer_id = res.singer_id;
                this.form.img = res.img;
                this.form.city_id = res.city_ids || [];
                this.form.sale_mode = res.sale_mode || [];
                this.form.ticket_type = res.ticket_type || [];
                this.form.is_sale = res.is_sale;
                this.form.is_seat = res.is_seat;
                this.form.is_realname = res.is_realname;
                this.form.allow_refund = res.allow_refund;
                this.form.refund_reason = res.refund_reason;
                this.form.service_desc = res.service_desc;
                this.form.instructions = res.instructions;
                // 退款规则
                let refund_rules = res.refund_rules || [];
                this.form.refund_rules = refund_rules.map(item =>{
                    return {
                        times: [item.start_time, item.end_time],
                        rate: parseFloat(item.rate)
                    }
                })
                // 地图
                this.form.address = res.address;
                this.form.lat = res.lat;
                this.form.lng = res.lng;
                this.$nextTick(() => {
                    this.$refs.map.setLocation({lng: res.lng, lat: res.lat, title: res.address});
                })
                // 初始化ue编辑器
                this.form.content = res.content;
                this.$refs.ueditor.init(res.content);
            }).catch(err => {
                this.$Message.error(err.message || '加载详情失败');
            })
        },
        handleSelectMap() {
            const addr = this.$refs.map.getAddress();
            this.form.address = addr.address;
            this.form.lat = addr.lat;
            this.form.lng = addr.lng;
            if(addr.address) {
                if(!addr.lat || !addr.lng) {
                    this.$Message.error('获取演出地点坐标失败');
                }
            }
        },
        handleSubmit(){
            if(this.submiting) return false;
            this.$refs.form.validate(valid => {
                if(valid){
                    const { form } = this;
                    if(!form.lat || !form.lng) {
                        this.$Message.error('获取演出地点坐标失败');
                        return false;
                    }
                    if (form.allow_refund === 1){
                        if (form.refund_rules.length === 0){
                            this.$Message.error('请完善退款规则配置');
                            return false;
                        }else{
                            for (var i = 0; i < form.refund_rules.length; i++) {
                                if (form.refund_rules[i].times === ''){
                                    this.$Message.error('请完善退款规则配置');
                                    return false;
                                }
                            };
                        }
                    }
                    let params = {
                        name: form.name,
                        category_id: form.category_id || 0,
                        tour_id: form.tour_id || 0,
                        singer_id: form.singer_id || 0,
                        img: form.img,
                        sale_mode: form.sale_mode,
                        ticket_type: form.ticket_type,
                        is_sale: form.is_sale,
                        is_seat: form.is_seat,
                        is_realname: form.is_realname,
                        address: form.address,
                        lat: form.lat,
                        lng: form.lng,
                        city_id: form.city_id[form.city_id.length - 1],
                        allow_refund: form.allow_refund,
                        refund_reason: form.refund_reason,
                        content:  this.$refs.ueditor.getUEContent(),
                        service_desc: form.service_desc,
                        instructions: form.instructions
                    }
                    // 格式化退款规则
                    if (form.allow_refund === 1){
                        params.refund_rules = form.refund_rules.map(item =>{
                            return {
                                start_time: formatDate(item.times[0], 'yyyy-MM-dd hh:mm'),
                                end_time: formatDate(item.times[1], 'yyyy-MM-dd hh:mm'),
                                rate: item.rate
                            }
                        })
                    }
                    this.submiting = true;
                    if(form.id) {
                        this.$ajax.put('/project/update/'+form.id, params).then(res=>{
                            this.$Message.success({
                                content: '编辑成功',
                                onClose: () => {
                                    this.handleCancel();
                                }
                            });
                        }).catch(err=>{
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }else{
                        this.$ajax.post('/project/save', params).then(res=>{
                            this.$Message.success({
                                content: '添加成功',
                                onClose: () => {
                                    this.$router.replace({name: 'project_concerts', query: {id: res.id}});
                                }
                            });
                        }).catch(err=>{
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }
                }
            })
        },
        // 取消
        handleCancel() {
            this.$router.back(-1);
        }
    }
};
</script>

<style lang="less">
.project-edit-form {
    .ivu-input-group {
        top: 0;
    }
    
    .textarea {
        .ivu-input {
            width: 280px;
        }
    }
    
    .ivu-select-placeholder {
        display: block;
    }
    
    .ivu-form-item-content {
        display: flex;
    }
    
    .ivu-cascader {
        .ivu-input {
            width: 300px;
        }
    }
}
</style>